package com.ganbo.ms.socket;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客户端发送一段话给服务端，服务端将内容显示在控制台上面
 */
public class TcpDemo {


    @Test
    public void client() throws IOException, InterruptedException {
        InetAddress inet = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inet, 8899);
        OutputStream os = socket.getOutputStream();
        while (true) {
            os.write("你好，我是客户端mm\n".getBytes());
            Thread.sleep(100);
        }
//        os.close();     //关闭流
//        socket.close(); //关闭socket
    }

    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(8899);
        while (true) {
            Socket socket = ss.accept();
            InputStream is = socket.getInputStream();
//        byte[] buffer = new byte[20];
//        int len;
//        while ((len = is.read(buffer)) != -1) {
//            String str = new String(buffer, 0, len);
//            System.out.println(str);
//        }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            System.out.println(baos.toString());
            socket.shutdownInput();


            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello client".getBytes());
            socket.shutdownOutput();

            outputStream.close();
            baos.close();
//            socket.close();
            is.close();
//            ss.close();
        }


    }

}
